<?php

namespace app\beautiful\controller\admin\mall;

use app\BaseController;

use app\common\logic\DataLogic;

use app\beautiful\model\mall\GoodsCategoryModel;

use app\beautiful\model\mall\GoodsModel;



class GoodsCategory extends BaseController{

    protected $name='商品分类';

    

    public function index()

    {
        $type = $this->request->param('type/d',0);
        $search = $this->request->param('search');
        $where = [

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

            ['pid','=',0]

        ];
        if($type>0) $where[] = ['type','=',$type];
        if($search) $where[]=['name','like','%'.$search.'%'];
        $order=['sort'=>'desc','category_id'=>'desc'];

        $append=['add_time_format'];

        $field="*";

        $category_model = new GoodsCategoryModel();

        $category_model = $category_model->withCount(['goods']);

        $return=DataLogic::getDataList($category_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        $return['list']=$this->getCategoryData($return['list']);

        return $this->success($return);

    }



    public function show()

    {

        //获取分类

        $categoryData=$this->getCategoryTreeData(0);



        $category_id=$this->request->param('category_id/d',0);

        if($category_id==0){

            return $this->success(['category'=>$categoryData]);

        }

        if(null === $category= GoodsCategoryModel::find($category_id))  return $this->error($this->name.'不存在');

        if($category->is_delete!=0)  return $this->error($this->name.'不存在');

        if($category->shop_id != $this->request->shopId)  return $this->error($this->name.'不存在');



        $detail=[

            'name'=>$category->name,

            'pid'=>$category->pid,

            'icon'=>$category->icon,

            'sort'=>$category->sort,

        ];

        return $this->success(['category'=>$categoryData,'detail'=>$detail]);

    }



    protected function getCategoryData($data)

    {

        if(!empty($data)){

            foreach ($data as $k  =>$v){

                $category=GoodsCategoryModel::withCount(['goods'])->where([

                    ['shop_id','=',$this->request->shopId],

                    ['is_delete','=',0],

                    ['pid','=',$v['category_id']]

                ])->order(['sort'=>'desc','category_id'=>'desc'])->select()->append(['add_time_format'])->toArray();

                if(!empty($category)){

                    $data[$k]['children']=$this->getCategoryData($category);

                }



            }

        }

        return $data;

    }



    protected function getCategoryTreeData($pid=0)

    {

        $return=[];

        $category= GoodsCategoryModel::where([

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

            ['pid','=',$pid]

        ])->select()->toArray();

        if(!empty($category)){

            foreach ($category as $k => $v){

                $return[$k]=[

                    'title'=>$v['name'],

                    'value'=>$v['category_id'],

                    'key'=>$v['category_id'],

                    'children'=>$v['category_id'] == 0 ? $this->getCategoryTreeData($v['category_id']) : [],

                ];

            }

        }

        if($pid == 0 ) array_unshift($return,['title'=>'设为父类','value'=>0,'key'=>0]);

        return $return;

    }



    public function save()

    {

        $category_id = $this->request->param('category_id/d',0);

        $name= $this->request->param('name');

        $pid= $this->request->param('pid/d',0);

        $icon = $this->request->param('icon');

        $sort = $this->request->param('sort/d',0);

        if(empty($name)) return $this->error('请输入名称');

        if($pid != 0){

            if(null === GoodsCategoryModel::where([

                    ['shop_id','=',$this->request->shopId],

                    ['is_delete','=',0],

                    ['category_id','=',$pid]

                ])->find()){

                return $this->error('父类不存在,请重新选择');

            }

        }

        if(empty($icon)) return $this->error('请上传图标');



        if($category_id != 0) {

            if(null === $category = GoodsCategoryModel::find($category_id))  return $this->error($this->name.'不存在');

            if($category->is_delete!=0)  return $this->error($this->name.'不存在');

            if($category->shop_id != $this->request->shopId)  return $this->error($this->name.'不存在');

            $pre_icon=$category->icon;

        }else{

            $category = new GoodsCategoryModel();

            $category->shop_id = $this->request->shopId;

            $pre_icon=null;

        }



        $category->name=$name;

        $category->pid=$pid;

        $category->icon=$icon;

        $category->sort=$sort;

        $category->save();



        //处理图片

        imgReplaceAct($icon,$pre_icon);

        return $this->success('保存成功');

    }



    public function del()

    {

        $category_id=$this->request->param('category_id/d',0);

        if(null === $category= GoodsCategoryModel::find($category_id))  return $this->error($this->name.'不存在');

        if($category->is_delete!=0)  return $this->error($this->name.'不存在');

        if($category->shop_id != $this->request->shopId)  return $this->error($this->name.'不存在');

        if($category_id && $category->is_no_update) return $this->error('该分类不能删除');



        if(null != GoodsCategoryModel::where([

                ['is_delete','=',0],

                ['shop_id','=',$this->request->shopId],

                ['pid','=',$category_id]

            ])->find()){

            return $this->error('该分类下面还有子分类未删除');

        }



        if(null != GoodsModel::where([

                ['is_delete','=',0],

                ['shop_id','=',$this->request->shopId],

                ['category_id','=',$category_id]

            ])->find()){

            return $this->error('该分类下面还有商品未删除');

        }



        $category->is_delete = 1;

        $category->save();



        return $this->success('删除成功');

    }

    /*多店版*/
    /**
     * 添加/修改分类
    */
    public function saveCategory()

    {

        $category_id = $this->request->param('category_id/d',0);

        $category_type = $this->request->param('category_type/d',0);//1父分类2子分类

        $type = $this->request->param('type/d',0);

        $name= $this->request->param('name');

        $pid = $this->request->param('pid/d',0);

        $status = $this->request->param('status/d',-1);

        if(empty($name)) return $this->error('请输入名称');

        if($category_type<1) return $this->error('分类类型参数有误');

        if($category_type==1 && $type<1) return $this->error('分类类别参数有误');

        if($category_type==2 && $pid<1) return $this->error('请选择父级分类');

        $category = GoodsCategoryModel::where(['name'=>$name,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();

        if($category && $category->category_id!=$category_id) return $this->error('该分类已存在');


        if($pid>0){
            $p_category = GoodsCategoryModel::where(['category_id'=>$pid,'is_delete'=>0,'shop_id'=>$this->request->shopId])->find();
            if(null === $p_category) return $this->error('父级不存在');
            $type = $p_category->type;
        }

        if($category_id != 0) {

            if(null === $category = GoodsCategoryModel::find($category_id))  return $this->error($this->name.'不存在');

            if($category->is_delete!=0)  return $this->error($this->name.'不存在');

            if($category->shop_id != $this->request->shopId)  return $this->error($this->name.'不存在');

            if($category->is_no_update) return $this->error('该分类不能修改');
        }else{

            $category = new GoodsCategoryModel();

            $category->shop_id = $this->request->shopId;

        }

        $category->name = $name;

        if($category_id<1) $category->type = $type;//修改时不能修改类别

        $category->pid = $pid;

        if($category_id<1 || ($category_id>0 && $status>0)) $category->status = $status;//新增（默认禁用）和修改状态为启用时才修改状态

        $category->save();


        return $this->success('保存成功');

    }
    /**
     * 修改状态/排序
    */
    public function saveInfo()

    {

        $category_id = $this->request->param('category_id/d',0);
        $status = $this->request->param('status','');
        $sort = $this->request->param('sort','');

        if(null === $category= GoodsCategoryModel::find($category_id))  return $this->error($this->name.'不存在');
        if($category->is_delete!=0)  return $this->error($this->name.'不存在');
        if($category->shop_id!=$this->request->shopId)  return $this->error($this->name.'不存在');

        if(in_array($status,[1,-1])) $category->status = $status;
        if(is_numeric($sort)) $category->sort = $sort;
        $category->save();

        return $this->success('保存成功');

    }
    public function sort(){
        $category_id = $this->request->param('category_id/d',0);
        $type = $this->request->param('type',null);
        if(empty($category_id)){
            return $this->error('分类ID错误');
        }
        if($type===null){
            return $this->error('type参数错误');
        }
        $where['category_id']=$category_id;
        $GoodsCategoryModel= new GoodsCategoryModel();
        $info=$GoodsCategoryModel->where(['category_id'=>$category_id])->find();
        if(empty($info)) return $this->error('该分类不存在');
        $s=[];
        $s['pid']=$info['pid'];
        $s['is_delete']=0;
        $order['sort']='desc';
        $order['category_id']='desc';
        $list=$GoodsCategoryModel->where($s)->order($order)
            ->limit(10000)->page(1)
            ->select()
            ->toArray();
        $brand_id=array_column($list,'category_id');
        if($type==1){//前移
            $new_brand=array_swap_forward($brand_id,$category_id);
        }elseif($type==2){//后移
            $new_brand=array_swap_back($brand_id,$category_id);
        }
        $count=count($new_brand);
        foreach ($new_brand as $k=>$v){
            $sort=$count-$k;
            $s=[];
            $s['category_id']=$v;
            GoodsCategoryModel::up(['sort'=>$sort],$s);
        }
        return $this->success();
    }


}

